# coding=utf-8
import json
import math
import traceback
from django.core.exceptions import ImproperlyConfigured
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.views.decorators.cache import cache_page

from common.errorcode import response_error
from common.requests import success_requests, err_requests, get_body, get_params
from models import Orginazation, CloudAuthUser, SubscriberCloudposition
from django.db.models import Count, Avg, Max, Min, Sum, Q
from django.db import connection, connections

# from subscriber.json_utils import CJsonEncoder
from django.contrib.auth.models import AbstractUser, User

from organize_manager.service import get_all_orguser


@cache_page(15)
def query_tree(request):
    """
    查询树结构
    :return:
    """
    try:
        tree_data = [{
            "text": "电信（陕西）云计算基地",
            "id": 0,
            "expanded": True,
        }]
        child_list = []
        child_org = Orginazation.objects.filter(parent_id=None).values('id', 'org_name').order_by("org_sort", "id")
        child_org = list(child_org)
        for org in child_org:
            child_org_dict = {}
            child_org_dict['id'] = org['id']
            child_org_dict['text'] = org['org_name']
            child_child = list(
                Orginazation.objects.filter(parent_id=org['id']).values('id', 'org_name').order_by("org_sort", "id"))
            for child_value in child_child:
                child_value["text"] = child_value.get("org_name")
                del child_value['org_name']
            child_org_dict["children"] = child_child
            child_list.append(child_org_dict)
        tree_data[0]['children'] = child_list
        return success_requests(tree_data)
    except:
        print traceback.format_exc()
        return err_requests('500')


def org_api_list(request):
    """
    组织机构列表API
    :param request:
    :return:
    """
    org_list = []
    try:
        # page = request.POST.get("page")
        # size = request.POST.get("size")
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        org_id = body.get("org_id")
        level = body.get("level")
        if level == 2:
            orgs = Orginazation.objects.filter(parent_id=org_id)
            if orgs.count() == 0:
                orgs = Orginazation.objects.filter(id=org_id)
        elif level == 3:
            orgs = Orginazation.objects.filter(id=org_id)
        else:
            orgs = Orginazation.objects.filter(parent_id=None)
        org_list = []
        for org in orgs:
            org_dict = {}
            org_dict["org_name"] = org.org_name
            org_dict["org_code"] = org.org_code
            org_dict["org_dec"] = org.org_dec
            org_dict["parent_code"] = org.parent_code
            if org.parent_id != None:
                org_dict["parent_name"] = org.parent_id.org_name
            else:
                org_dict["parent_name"] = "电信（陕西）云计算基地"
            id = org.id
            org_dict["id"] = id
            org_dict["count"] = CloudAuthUser.objects.filter(Q(org=id) | Q(org__parent_id=id)).count()
            org_list.append(org_dict)
        # import json
        # data = json.dumps(org_list)
        return success_requests(org_list)
    except Exception as e:
        print traceback.format_exc()
        return err_requests('500')


def authorg_api_list(request):
    """
    用户组织机构列表API
    :param request:
    :return:
    """
    org_list = []
    try:
        # page = request.POST.get("page")
        # size = request.POST.get("size")
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        org_id = body.get("org_id")
        level = body.get("level")
        if level == 2:
            orgs = Orginazation.objects.filter(parent_id=org_id)
            if orgs.count() == 0:
                orgs = Orginazation.objects.filter(id=org_id)
        elif level == 3:
            orgs = Orginazation.objects.filter(id=org_id)
        else:
            orgs = Orginazation.objects.filter(parent_id=None)
        org_list = []
        for org in orgs:
            org_dict = {}
            org_dict["org_name"] = org.org_name
            org_dict["org_code"] = org.org_code
            org_dict["org_dec"] = org.org_dec
            org_dict["parent_code"] = org.parent_code
            if org.parent_id != None:
                org_dict["parent_name"] = org.parent_id.org_name
            else:
                org_dict["parent_name"] = "电信（陕西）云计算基地"
            id = org.id
            org_dict["id"] = id
            org_dict["count"] = CloudAuthUser.objects.filter(Q(org=id) | Q(org__parent_id=id)).count()
            org_list.append(org_dict)
        return success_requests(org_list)
    except Exception as e:
        print traceback.format_exc()
        return err_requests('500')


def query_org_list(request):
    """
    查询组织列表
    :return:
    """
    org_list = []
    try:
        # page = request.POST.get("page")
        # size = request.POST.get("size")
        org_id = request.POST.get("org_id")
        if org_id:
            orgs = Orginazation.objects.filter(id=org_id)
        else:
            orgs = Orginazation.objects.all()
        org_list = []
        for org in orgs:
            org_dict = {}
            org_dict["org_name"] = org.org_name
            org_dict["org_code"] = org.org_code
            org_dict["org_dec"] = org.org_dec
            org_dict["parent_code"] = org.parent_code
            id = org.id
            org_dict["count"] = CloudAuthUser.objects.filter(Q(org=id) | Q(org__parent_id=id)).count()
            org_list.append(org_dict)
        return render(request, "orginazation/systemMgr/organizationMgr.html", {"org_list": org_list})
    except Exception as e:
        print traceback.format_exc()
        return err_requests('500')


def query_original(request):
    """
    查询父组织
    :return:
    """
    try:
        import json
        body = json.loads(request.body)
        org_id = body.get("org_id")
        if org_id:
            parent_id = Orginazation.objects.filter(id=org_id).values("parent_id")[0].get("parent_id")
            if parent_id:
                result = Orginazation.objects.filter(id=parent_id).values()
            else:
                result = Orginazation.objects.filter(id=org_id).values()
            result = list(result)[0]
        else:
            result = {"id": 0, "org_name": "电信（陕西）云计算基地"}
        return success_requests(result)
    except:
        print traceback.format_exc()
        return err_requests("500")


def query_authoriginal(request):
    """
    查询用户组织
    :return:
    """
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        org_id = body.get("org_id")
        if org_id:
            result = Orginazation.objects.filter(id=org_id).values()
            result = list(result)[0]
        else:
            result = {"id": 0, "org_name": "电信（陕西）云计算基地"}
        return success_requests(result)
    except:
        print traceback.format_exc()
        return err_requests("500")


def add_org_info(request):
    """
    添加组织信息
    :return:
    """
    try:
        org_body = {}
        body = get_body(request)
        parent_id = body.get("parent_id")
        org_body['org_name'] = body.get('name')
        org_body['org_code'] = body.get('code')
        org_body['parent_code'] = body.get('pDept')
        org_body['org_dec'] = body.get('description')
        if parent_id:
            org_body['parent_id'] = Orginazation.objects.get(id=parent_id)
        else:
            org_body['parent_id'] = None
        Orginazation.objects.create(**org_body)
        return success_requests()
    except Exception as e:
        print traceback.format_exc()
        return err_requests("500")


def edit_org_info(request):
    """
    编辑组织信息
    :return:
    """
    try:
        body = get_body(request)
        org_id = body['id']
        orgs = Orginazation.objects.filter(id=org_id)
        result = {}
        for org in orgs:
            result["id"] = org.id
            result["parent_code"] = org.parent_code
            result["org_name"] = org.org_name
            result["org_code"] = org.org_code
            result["org_dec"] = org.org_dec
            if org.parent_id:
                result["parent_id"] = org.parent_id.id
                result["parent_name"] = org.parent_id.org_name
            else:
                result["parent_id"] = 0
                result["parent_name"] = "电信（陕西）云计算基地"
        return success_requests(result)
    except:
        print traceback.format_exc()
        return err_requests("500")


def update_org_info(request):
    """
    更新组织信息
    :return:
    """
    try:
        org_body = {}
        body = get_body(request)
        id = body.get('id')
        org_body['id'] = id
        org_body['org_name'] = body['name']
        org_body['org_code'] = body['code']
        if body['pDept'] == "-":
            org_body['parent_code'] = "-"
        else:
            org_body['parent_code'] = "+"
        org_body['org_dec'] = body['description']
        Orginazation.objects.filter(id=id).update(**org_body)
        return success_requests()
    except:
        print traceback.format_exc()
        return err_requests("500")


def delete_org_info(request):
    """
    删除组织信息
    :return:
    """
    try:
        # print request
        # id = int(request.GET.get('id'))
        body = get_body(request)
        id = body['id']
        idstring = ",".join(id)
        Orginazation.objects.extra(where=['id IN (' + idstring + ')']).delete()
        return success_requests()
    except:
        print traceback.format_exc()
        return err_requests("500")


def my_custom_sql_view(request):
    from django.db import connection
    org_list = []
    try:
        cursor = connection.cursor()
        cursor.execute("SELECT  org.*, COUNT(ur.id) as count FROM orginazation_orginazation  org " \
                       "LEFT JOIN cloud_auth_user ur ON org.id = ur.org_id GROUP BY org.id ")
        org_list = dict_fetchall(cursor)
    except Exception as e:
        print traceback.format_exc()
    return org_list


def dict_fetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]


def author_api_list(request):
    org_list = []
    try:
        # page = request.POST.get("page")
        # size = request.POST.get("size")
        org_id = request.POST.get("org_id")
        users = CloudAuthUser.objects.filter(
            Q(org=org_id) | Q(org__parent_id=org_id) | Q(cloud_is_delete=0))  # .values()
        org_list = {"user_list": [], "count": users.count()}
        for user in users:
            user_dict = {}
            user_dict["username"] = user.author.username
            user_dict["email"] = user.author.email
            user_dict["cloud_phone"] = user.cloud_phone
            user_dict["cloud_sex"] = user.cloud_sex
            user_dict["cloud_status"] = user.cloud_status
            org_list["user_list"].append(user_dict)
        return success_requests(org_list)
    except Exception as e:
        print traceback.format_exc()
        return err_requests('500')


def query_user_list(request):
    """
    查询人员列表
    :return:
    """
    user_list = []
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        org_id = body.get("org_id")
        if org_id:
            users = CloudAuthUser.objects.filter(Q(org=org_id) | Q(org__parent_id=org_id))
        else:
            users = CloudAuthUser.objects.all()
        for user in users:
            user_dict = {}
            user_dict["cloud_phone"] = user.cloud_phone
            user_dict["cloud_sex"] = user.cloud_sex
            user_dict["cloud_status"] = user.cloud_status
            user_dict["cloud_is_delete"] = user.cloud_is_delete
            user_dict["username"] = user.author.username
            user_dict["realname"] = user.realname
            user_dict["id"] = user.id
            if user.org:
                user_dict["org_name"] = user.org.org_name
            else:
                user_dict["org_name"] = "电信（陕西）云计算基地"
            if user.position:
                user_dict["position"] = user.position.id
                user_dict["position_name"] = user.position.position_name
            else:
                user_dict["position"] = None
                user_dict["position_name"] = "离职"
            user_dict["id"] = user.id
            if user.position:
                user_dict["position"] = user.position.position_name
            user_list.append(user_dict)
        
        return success_requests({'user_list': user_list})
    except:
        print traceback.format_exc()
        err_requests('500')


def query_position_list(request):
    """
    查询岗位列表
    :return:
    """
    try:
        position_list = list(SubscriberCloudposition.objects.all().values())
        return success_requests(position_list)
    except Exception as e:
        print e
        return err_requests("500")


def add_user_info(request):
    """
    添加人员信息
    :return:
    """
    try:
        body = get_body(request)
        user_params = get_params(body, {"username": "name", "password": "pwd"}, {"email": "email"},
                                 email="123123@qq.com")
        if isinstance(user_params, JsonResponse):
            return user_params
        user = User.objects.create_user(**user_params)
        cloudauth_params = get_params(body, {"cloud_phone": "phoneNum", "realname": "firstName", "cloud_sex": "gender"},
                                      {"position": "position", "cloud_status": "status", "org": "org_id"}, status=0)
        cloudauth_params["author"] = user
        if cloudauth_params["position"]:
            cloudauth_params["position"] = SubscriberCloudposition.objects.filter(id=cloudauth_params["position"])[0]
        if cloudauth_params.get("org") != None:
            cloudauth_params["org"] = Orginazation.objects.filter(id=cloudauth_params.get("org"))[0]
        if isinstance(cloudauth_params, JsonResponse):
            return cloudauth_params
        CloudAuthUser.objects.create(**cloudauth_params)
        return success_requests()
    except Exception as e:
        print e
        return err_requests("500")


def edit_user_info(request):
    """
    编辑人员信息
    :return:
    """
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        id = body.get('id')
        users = CloudAuthUser.objects.filter(id=id)
        if users.count() == 0:
            return err_requests("500")
        result = {}
        for user in users:
            result["phoneNum"] = user.cloud_phone
            result["firstName"] = user.realname
            result["gender"] = user.cloud_sex
            result["status"] = user.cloud_status
            result["pwd"] = "******"
            if user.org:
                result["org_name"] = user.org.org_name
                result["org_id"] = user.org.id
            else:
                result["org_name"] = "电信（陕西）云计算基地"
                result["org_id"] = 0
            if user.position:
                result["position"] = user.position.id
                result["position_name"] = user.position.position_name
            else:
                result["position"] = None
                result["position_name"] = "离职"
            result["name"] = user.author.username
            result["id"] = user.id
            break
        return success_requests(result)
    except Exception as e:
        print e
        return err_requests("500")


def update_user_info(request):
    """
    更新人员信息
    :return:
    """
    try:
        body = get_body(request)
        if body.get("id") is None:
            return None
        cloudauthor = CloudAuthUser.objects.filter(id=body.get("id"))[0]
        if cloudauthor is None:
            return err_requests("505")
        author = User.objects.filter(id=cloudauthor.author.id)
        user_params = get_params(body, {"username": "name", "password": "pwd"}, {"email": "email"},
                                 email="123123@qq.com")
        if isinstance(user_params, JsonResponse):
            return user_params
        password = user_params["password"]
        if password:
            if password == "******":
                del user_params["password"]
            elif len(password) < 6:
                del user_params["password"]
        else:
            del user_params["password"]
        author.username = user_params.get("username")
        if user_params.get("password"):
            author.set_password(password)
        
        cloudauth_params = get_params(body, {"cloud_phone": "phoneNum", "realname": "firstName", "cloud_sex": "gender"},
                                      {"position": "position", "cloud_status": "status", "org": "org_id"}, status=0)
        if cloudauth_params.get("org") != None:
            cloudauth_params["org"] = Orginazation.objects.filter(id=cloudauth_params.get("org"))[0]
        if isinstance(cloudauth_params, JsonResponse):
            return cloudauth_params
        CloudAuthUser.objects.filter(id=body.get("id")).update(**cloudauth_params)
        return success_requests()
    except Exception as e:
        print e
        return err_requests("500")


def delete_user_info(request):
    """
    删除用户信息
    :return:
    """
    try:
        body = get_body(request)
        id = body['id']
        idstring = ",".join(id)
        author_ids = []
        users = CloudAuthUser.objects.extra(where=['id IN (' + idstring + ')'])
        for user in users:
            author_ids.append(str(user.author.id))
        idstring = ",".join(author_ids)
        User.objects.extra(where=['id IN (' + idstring + ')']).delete()
        return success_requests()
    except Exception as e:
        print e
        return err_requests


def forget_user_password(request):
    """
    忘记密码
    :return:
    """
    try:
        body = get_body(request)
        id = body.get("id")
        password = body.get("password")
        authors = CloudAuthUser.objects.filter(id=id)
        for author in authors:
            author = author.author
            author.set_password(password)
            author.save()
            break
        return success_requests()
    except Exception as e:
        print e
        return err_requests


def my_user_sql_view(request):
    from django.db import connection
    user_list = []
    try:
        cursor = connection.cursor()
        cursor.execute("SELECT  u.id, u.password, u.last_login, u.is_superuser, u.username, u.first_name,"
                       " u.last_name, u.email, u.is_staff, u.is_active, u.cloud_phone, u.cloud_sex, "
                       "u.cloud_status, u.cloud_is_delete, o.org_name, s.position_name "
                       "FROM docloud_child.cloud_auth_user AS u " \
                       "LEFT JOIN  orginazation_orginazation AS o ON  u.org_id = o.id " \
                       "LEFT JOIN  subscriber_cloudposition AS s ON  u.position_id = s.id ")
        user_list = dict_fetchall(cursor)
    except Exception as e:
        print traceback.format_exc()
    return user_list


def dict_fetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]


def add_position_api(request):
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        position_params = get_params(body, {"position_name": "postName"}, {"remarks": "description"})
        if isinstance(position_params, JsonResponse):
            return position_params
        SubscriberCloudposition.objects.create(**position_params)
        return success_requests()
    except Exception as e:
        print e
        return err_requests("505")


def delete_position_api(request):
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        
        id = body.get("id")
        if id is None:
            return err_requests("505")
        
        SubscriberCloudposition.objects.filter(id=id).delete()
        
        return success_requests()
    except Exception as e:
        print e
        return err_requests("505")


def edit_position_api(request):
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        
        id = body.get("id")
        if id is None:
            return err_requests("505")
        
        positions = SubscriberCloudposition.objects.filter(id=id)
        
        result = {}
        for position in positions:
            result["postName"] = position.position_name
            result["description"] = position.remarks
            result["id"] = position.id
            break
        
        return success_requests(result)
    except Exception as e:
        print e
        return err_requests("505")


def update_position_api(request):
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        
        id = body.get("id")
        if id is None:
            return err_requests("505")
        
        position_params = get_params(body, {"position_name": "postName"}, {"remarks": "description"})
        if isinstance(position_params, JsonResponse):
            return position_params
        SubscriberCloudposition.objects.filter(id=id).update(**position_params)
        return success_requests()
    except Exception as e:
        print e
        return err_requests("505")


@cache_page(60 * 15)
def get_orguser_api(request):
    org_users = get_all_orguser()
    return success_requests(org_users)
